package net.socket;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Redirector implements Runnable
{
	private int port;
	private String newSite;
	public Redirector(String site,int port)
	{
		this.port = port;
		this.newSite = site;
	}
	@Override
	public void run()
	{
		try
		{
			ServerSocket server = new ServerSocket(this.port);
			System.out.println(server.getLocalPort());
			while(true)
			{
				try
				{
					Socket s = server.accept();
					Thread t = new RedirectThread(s);
					t.start();
				}
				catch (Exception e)
				{
				}
			}
		}
		catch (Exception e)
		{
		}
	}
	class RedirectThread extends Thread
	{
		private Socket connection;
		public RedirectThread(Socket s)
		{
			this.connection = s;
		}
		@Override
		public void run()
		{
			try
			{
				Writer out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "ASCII"));
				Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
				StringBuffer request = new StringBuffer(80);
				while(true)
				{
					int c = in.read();
					if(c=='\r'||c=='\n'||c==-1)
					{
						break;
					}
					request.append((char)c);
				}
				String get = request.toString();
				int firstSpace = get.indexOf(' ');
				int secondSpace = get.indexOf(' ',firstSpace+1);
				String theFile = get.substring(firstSpace+1, secondSpace);
				if(get.indexOf("HTTP")!=-1)
				{
					out.write("HTTP/1.0 302 FOUND\r\n");
					Date date = new Date();
					out.write("Date:"+date.toString()+"\r\n");
					out.write("Server:Redirector 1.0\r\n");
					out.write("Location:"+newSite+theFile+"\r\n");
					out.write("Content-type:text/html\r\n\r\n");
					out.flush();
				}
				out.write("<html><head><title></title></head><body>move</body></html>");
				out.flush();
			}
			catch (Exception e)
			{
			}
			finally
			{
				try
				{
					if(connection!=null)
					{
						connection.close();
					}
				}
				catch (Exception e2)
				{
				}
			}
		}
	}
	public static void main(String[] args)
	{
		int thePort;
		String theSite;
		try
		{
			theSite = args[0];
			if(theSite.endsWith("/"))
			{
				theSite = theSite.substring(0,theSite.length()-1);
			}
		}
		catch (Exception e)
		{
			return;
		}
		try
		{
			thePort = Integer.parseInt(args[1]);
		}
		catch (Exception e)
		{
			thePort = 80;
		}
		Thread t = new Thread(new Redirector(theSite, thePort));
		t.start();
	}
}

